/*
 * JSMuffin - Another javascript canvas framework.
 * @author xshifty
 */

if (muffin && muffin.Canvas) muffin.Poly = muffin.Poly || muffin.Class({
	events:{
		onclick:function () {},
		onmousemove:function () {},
		onmousedown:function () {},
		onmouseup:function () {}
	},
	init:function (defaults_) {
		muffin.extend(this, {
			'backgroundColor':'#000',
			'borderColor':'#fff',
			'borderSize':1,
			'closePath':false,
			'coords':[{'x':10,'y':10}, {'x':10,'y':30}, {'x':30,'y':30}]
		}, defaults_);
	},
	renderize:function (ctx_, map_) {
		var ctx = ctx_ || false;
		var bounds = this.getBounds();
		var map = map_ ? {'x':bounds.x,'y':bounds.y} : {'x':0, 'y':0};

		if (!!ctx.toString().match(/CanvasRenderingContext2D/g) && this.coords.length > 1) {
			var coord = this.coords[0];

			if (typeof this.backgroundColor == 'string') ctx.fillStyle = this.backgroundColor;
			if (typeof this.borderColor == 'string') ctx.strokeStyle = this.borderColor;
			if (typeof this.borderSize == 'number') ctx.lineWidth = this.borderSize;

			ctx.beginPath();
			ctx.moveTo(coord.x - map.x, coord.y - map.y);

			for (var i = 1; i < this.coords.length; i++) {
				coord = this.coords[i];
				ctx.lineTo(coord.x - map.x, coord.y - map.y);
			}

			if (!!this.closePath) ctx.closePath();
			if (typeof this.backgroundColor == 'string') ctx.fill();
			if (typeof this.borderColor == 'string') ctx.stroke();
		}
	},
	getBounds:function () {
		var minCoord = {'x':this.coords[0].x,'y':this.coords[0].y};
		var maxCoord = {'x':0,'y':0};
		var bounds = {'x':0,'y':0,'width':0,'height':0};
		
		for (var i in this.coords) {
			coord = this.coords[i];
			
			minCoord.x = coord.x < minCoord.x ? coord.x : minCoord.x;
			minCoord.y = coord.y < minCoord.y ? coord.y : minCoord.y;
			maxCoord.x = coord.x > maxCoord.x ? coord.x : maxCoord.x;
			maxCoord.y = coord.y > maxCoord.y ? coord.y : maxCoord.y;
		}
		
		bounds.x = minCoord.x;
		bounds.y = minCoord.y;
		bounds.width = maxCoord.x - minCoord.x;
		bounds.height = maxCoord.y - minCoord.y;
		
		delete(minCoord);
		delete(maxCoord);
		
		return bounds;
	}
});